package com.atty.dms.controller;

import com.atty.dms.common.convention.exception.ClientException;
import com.atty.dms.common.convention.result.Result;
import com.atty.dms.common.convention.result.Results;
import com.atty.dms.dao.entity.InterestDO;
import com.atty.dms.dao.entity.UserInterestDO;
import com.atty.dms.dao.mapper.UserInterestMapper;
import com.atty.dms.dto.req.BatchUserInterestCreateReqDTO;
import com.atty.dms.dto.req.SingleUserInterestUpdateReqDTO;
import com.atty.dms.dto.resp.UserInterestRespDTO;
import com.atty.dms.dto.resp.UserRespDTO;
import com.atty.dms.service.InterestService;
import com.atty.dms.service.UserInterestService;
import com.atty.dms.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: UserInterestController
 * Package: com.atty.dms.controller
 * Description:
 *
 * @Author: tony
 * @Create: 2025/4/19 9:08
 * @Version: 1.0
 */
@RestController
@RequiredArgsConstructor
public class UserInterestController {

    private final UserService userService;
    private final UserInterestService userInterestService;
    private final UserInterestMapper userInterestMapper;
    private final InterestService interestService;

    /**
     * 根据用户ID获取兴趣信息
     */
    @GetMapping("/api/dms/admin/user-interest/user/{userId}")
    public Result<UserInterestRespDTO> getUserInterestsByUserId(@PathVariable Long userId) {
        UserRespDTO UserRespDTO = userService.getUserByUserId(userId);
        List<String> interestNames = userInterestService.getInterestNamesByUserId(userId);
        if (interestNames.isEmpty()) {
            throw new ClientException("该用户没有关联的兴趣信息");
        }
        UserInterestRespDTO userInterestRespDTO = new UserInterestRespDTO();
        userInterestRespDTO.setUsername(UserRespDTO.getUsername());
        userInterestRespDTO.setInterestName(interestNames);
        userInterestRespDTO.setUserId(userId);
        return Results.success(userInterestRespDTO);
    }

    /**
     * 根据用户名获取兴趣信息
     */
    @GetMapping("/api/dms/admin/user-interest/username/{username}")
    public Result<UserInterestRespDTO> getUserInterestsByUsername(@PathVariable String username) {
        UserRespDTO UserRespDTO = userService.getUserByUsername(username);
        List<String> interestNames = userInterestService.getInterestNamesByUserId(UserRespDTO.getUserId());
        if (interestNames.isEmpty()) {
            throw new ClientException("该用户没有关联的兴趣信息");
        }
        UserInterestRespDTO userInterestRespDTO= new UserInterestRespDTO();
        userInterestRespDTO.setUsername(UserRespDTO.getUsername());
        userInterestRespDTO.setInterestName(interestNames);
        userInterestRespDTO.setUserId(UserRespDTO.getUserId());
        return Results.success(userInterestRespDTO);
    }


    /**
     * 创建单个用户兴趣
     */
    @PostMapping("/api/dms/admin/user-interest/single")
    public Result<Void> createUserInterest(@RequestParam Long userId, @RequestParam Long interestId) {
        userInterestService.createUserInterest(userId, interestId);
        return Results.success();
    }

    /**
     * 批量创建用户兴趣
     */
    @PostMapping("/api/dms/admin/user-interest/batch")
    public Result<Void> batchCreateUserInterests(@RequestBody @Valid BatchUserInterestCreateReqDTO requestParam) {
        userInterestService.batchCreateUserInterests(requestParam);
        return Results.success();
    }

    /**
     * 删除单个用户单个兴趣
     */
    @DeleteMapping("/api/dms/admin/user-interest/single")
    public Result<Void> deleteUserInterest(@RequestParam Long userId, @RequestParam Long interestId) {
        userInterestService.deleteUserInterest(userId, interestId);
        return Results.success();
    }







    /**
     * 删除单个用户多个兴趣
     */
    @DeleteMapping("/api/dms/admin/user-interest/batch")
    public Result<Void> deleteUserInterests(@RequestBody @Valid BatchUserInterestCreateReqDTO requestParam) {
            userInterestService.deleteUserInterests(requestParam);
        return Results.success();
    }

    /**
     * 修改单个用户兴趣
     */
    @PutMapping("/api/dms/admin/user-interest/single")
    public Result<Void> updateUserInterest(@RequestBody @Valid SingleUserInterestUpdateReqDTO requestParam) {
        userInterestService.updateUserInterest(requestParam);
        return Results.success();
    }


    /**
     * 根据兴趣ID获取用户信息
     */
    @GetMapping("/api/dms/admin/user-interest/interest/{interestId}")
    public Result<List<String>> getUsernamesByInterestId(@PathVariable Long interestId) {
        List<String> usernames = userInterestService.getUsernamesByInterestId(interestId);
        if (usernames.isEmpty()) {
            throw new ClientException("没有用户关联此兴趣");
        }
        return Results.success(usernames);
    }


    /**
     * 分页获取用户兴趣信息
     */
    @GetMapping("/api/dms/admin/user-interest/page")
    public Result<Page<String>> getPageUserInterests(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        Page<UserInterestDO> page = new Page<>(pageNum, pageSize);
        IPage<UserInterestDO> userInterestsPage = userInterestMapper.selectPage(page, null); // 执行分页查询

        if (userInterestsPage.getRecords().isEmpty()) {
            throw new ClientException("没有找到用户兴趣信息");
        }
        // 使用 InterestService 直接获取兴趣名称
        List<String> interestNames = userInterestsPage.getRecords().stream()
                .map(userInterest -> {
                    InterestDO interestDO = interestService.getById(userInterest.getInterestId());
                    if (interestDO == null) {
                        return "未知兴趣(" + userInterest.getInterestId() + ")";
                    }
                    return interestDO.getName(); // 假设 getName() 返回兴趣名称
                })
                .collect(Collectors.toList());

        // 创建一个新的 Page 对象来存储兴趣名称
        Page<String> resultPage = new Page<>(pageNum, pageSize);
        resultPage.setRecords(interestNames);
        resultPage.setTotal(userInterestsPage.getTotal());
        resultPage.setSize(userInterestsPage.getSize());
        resultPage.setCurrent(userInterestsPage.getCurrent());

        return Results.success(resultPage);
    }

}